/*
 * @lc app=leetcode.cn id=1305 lang=typescript
 *
 * [1305] 两棵二叉搜索树中的所有元素
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] {
  // 中序遍历，取出搜索树的递增序列
  const inorder = (root: TreeNode, result: number[]) => {
    if (root === null) return;
    inorder(root.left, result);
    result.push(root.val);
    inorder(root.right, result);
  };

  const result1 = [];
  inorder(root1, result1);
  const result2 = [];
  inorder(root2, result2);
  let i = 0;
  let j = 0;
  const ans = [];
  // 二路归并
  while (i < result1.length || j < result2.length) {
    if (j >= result2.length || (i < result1.length && result1[i] <= result2[j])) {
      ans.push(result1[i]);
      i++;
    } else {
      ans.push(result2[j]);
      j++;
    }
  }

  return ans;
}
// @lc code=end
